//
//  ZHPlayerView.m
//  AVPlayerDemo
//
//  Created by 正合适 on 2017/10/28.
//  Copyright © 2017年 正合适. All rights reserved.
//

#import "ZHPlayerView.h"
#import "ZHBaseAVPlayerView.h"
#import "ZHPlayerProgressView.h"
#import "ZHBaseAVPlayerHelper.h"
#import "ZHPlayerGesturesView.h"

@interface ZHPlayerView ()<ZHBaseAVplayerProtocol, ZHPlayerGesturesViewProtocol>

/**player view*/
@property (nonatomic, strong) ZHBaseAVPlayerView *playerView;
/**播放暂停按钮*/
@property (nonatomic, strong) UIButton *playBtn;
/**进度条*/
@property (nonatomic, strong) ZHPlayerProgressView *progressView;
/**视频总时间 秒*/
@property (nonatomic, assign) float videoTotalTime;
/**视频当前时间*/
@property (nonatomic, assign) float videoCurrentTime;
/**是否在拖动中*/
@property (nonatomic, assign) BOOL isDraging;
/**时间label*/
@property (nonatomic, strong) UILabel *timeLabel;
/**底部操作栏view*/
@property (nonatomic, strong) UIView *toolView;
/**全屏按钮*/
@property (nonatomic, strong) UIButton *fullScreenBtn;
/**全屏手势按钮*/
@property (nonatomic, strong) ZHPlayerGesturesView *gestureView;
/**是否隐藏toolview*/
@property (nonatomic, assign) BOOL isHideToolView;
/**是否可以拖动*/
@property (nonatomic, assign) BOOL bDrag;
@end

@implementation ZHPlayerView
- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self defaultDatas];
        [self createUI];
    }
    return self;
}

- (void)dealloc {
    NSLog(@"---------- ZHPlayerView-视屏播放控件被释放 ----------");
}

#pragma mark - 初始数据
- (void)defaultDatas {
    _videoTotalTime = 0.0;
    _videoCurrentTime = 0.0;
    _isDraging = NO;
    _isHideToolView = NO;
    _bDrag = YES;
}

#pragma mark - 初始化界面
- (void)createUI {
    __weak typeof(self) weakSelf = self;
    self.clipsToBounds = YES;
    ZHBaseAVPlayerConfiguration *config = [[ZHBaseAVPlayerConfiguration alloc] init];
    [config configAutoPlay:YES];
    _playerView = [[ZHBaseAVPlayerView alloc] initWithFrame:self.bounds configuration:config];
    _playerView.delegate = self;
    [self addSubview:_playerView];
    
    _gestureView = [[ZHPlayerGesturesView alloc] initWithFrame:self.bounds];
    _gestureView.delegate = self;
    _gestureView.backgroundColor = ZHRGBAColor(0, 0, 0, 0);
    [self addSubview:_gestureView];
    
    _toolView = [[UIView alloc] initWithFrame:CGRectMake(0, self.frame.size.height-40, self.frame.size.width, 40)];
    _toolView.backgroundColor = ZHRGBAColor(0, 0, 0, 0.4);
    [self addSubview:_toolView];
    
    // 播放暂停按钮
    _playBtn = [[UIButton alloc] initWithFrame:CGRectMake(5, (_toolView.frame.size.height-20)/2.0, 20, 20)];
    [_playBtn setImage:[UIImage imageNamed:@"ZHUIKit.bundle/zhplayer_play"] forState:UIControlStateNormal];
    [_playBtn setImage:[UIImage imageNamed:@"ZHUIKit.bundle/zhplayer_pause"] forState:UIControlStateSelected];
    [_playBtn addTarget:self action:@selector(playAction:) forControlEvents:UIControlEventTouchUpInside];
    _playBtn.selected = NO;
    [_toolView addSubview:_playBtn];
    
    // 全屏按钮
    _fullScreenBtn = [[UIButton alloc] initWithFrame:CGRectMake(_toolView.frame.size.width-20-5, (_toolView.frame.size.height-20)/2.0, 20, 20)];
    [_fullScreenBtn setImage:[UIImage imageNamed:@"ZHUIKit.bundle/zhquanping"] forState:UIControlStateNormal];
    [_fullScreenBtn addTarget:self action:@selector(fullScreenAction) forControlEvents:UIControlEventTouchUpInside];
    [_toolView addSubview:_fullScreenBtn];
    
    // 进度条
    float progressX = _playBtn.frame.origin.x+_playBtn.frame.size.width+5;
    float progressW = _fullScreenBtn.frame.origin.x - progressX - 10;
    _progressView = [[ZHPlayerProgressView alloc] initWithFrame:CGRectMake(progressX, 0, progressW, _toolView.frame.size.height)];
    _progressView.dragBlcok = ^(NSInteger status, float bfb) {
        [weakSelf dragActionWithStatus:status bfb:bfb];
    };
    [_toolView addSubview:_progressView];
    
    float timeW = (_progressView.frame.origin.x + _progressView.frame.size.width);
    _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, _toolView.frame.size.height-15, timeW, 15)];
    _timeLabel.textAlignment = NSTextAlignmentRight;
    _timeLabel.textColor = [UIColor whiteColor];
    _timeLabel.font = [UIFont systemFontOfSize:12];
    _timeLabel.text = @"-:-/-:-";
    [_toolView addSubview:_timeLabel];
    
    _playerView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _toolView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    _gestureView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    _playBtn.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
    _fullScreenBtn.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
    _timeLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
    
}

#pragma mark - 配置播放url
- (void)configVideoPlayerUrl:(NSString *)videoUrl {
    if (videoUrl.length > 0) {
        [_playerView loadVideoWithUrl:videoUrl];
    }
}

#pragma mark - 播放Action
- (void)playAction:(UIButton *)sender {
    if (sender.selected) {
        [_playerView pause];
    } else {
        [_playerView play];
    }
}

#pragma mark - 视频资源加载成功Action
- (void)videoSourceLoadSuccessActionWithTotalTime:(float)totalTime {
    _videoTotalTime = totalTime;
    [self setTimeLabel];
}

#pragma mark - 拖动Action 0:开始 1：拖动中 2：拖动结束
- (void)dragActionWithStatus:(NSInteger)status bfb:(float)bfb {
    if (status == 0) {
        // 开始拖动
        _isDraging = YES;
    } else if (status == 1) {
        // 拖动中
        _videoCurrentTime = bfb*_videoTotalTime;
        [self setTimeLabel];
    } else if (status == 2) {
        // 跳转到指定时间的视频
        [self jumpToAppointTimeToPlay:bfb*_videoTotalTime];
        // 延迟1秒执行，修改拖动结束的状态
        [self performSelector:@selector(delayAction) withObject:nil afterDelay:1];
    }
}

- (void)delayAction {
    // 拖动结束
    _isDraging = NO;
}

#pragma mark - 隐藏工具栏
- (void)hideToolView {
    __weak typeof(self) weakSelf = self;
    float y = _isHideToolView ? self.frame.size.height-_toolView.frame.size.height : self.frame.size.height;
    [UIView animateWithDuration:0.3 animations:^{
        weakSelf.toolView.frame = CGRectMake(weakSelf.toolView.frame.origin.x, y, weakSelf.toolView.frame.size.width, weakSelf.toolView.frame.size.height);
    } completion:^(BOOL finished) {
        weakSelf.isHideToolView = !weakSelf.isHideToolView;
    }];
}

#pragma mark - 全屏按钮Action
- (void)fullScreenAction {
    if (self.delegate && [self.delegate respondsToSelector:@selector(fullScreentWithZHPlayerView:)]) {
        [self.delegate fullScreentWithZHPlayerView:self];
    }
}

#pragma mark - 视频跳转到指定播放时间
- (void)jumpToAppointTimeToPlay:(float)time {
    [_playerView seekToTime:time];
}

#pragma mark - 播放指定时间
- (void)configVideoToTime:(float)time {
    [self jumpToAppointTimeToPlay:time];
}

#pragma mark - 是否可以拖动
- (void)configDrag:(BOOL)bDrag {
    _bDrag = bDrag;
    _progressView.userInteractionEnabled = _bDrag;
}


#pragma mark - 设置时间
- (void)setTimeLabel {
    NSString *str1 = [ZHBaseAVPlayerHelper translateMMSSFromSS:_videoCurrentTime];
    NSString *str2 = [ZHBaseAVPlayerHelper translateMMSSFromSS:_videoTotalTime];
    _timeLabel.text = [NSString stringWithFormat:@"%@/%@",str1,str2];
}

- (void)play {
    [_playerView play];
}

- (void)pause {
    [_playerView pause];
}

#pragma mark - ZHBaseAVplayerProtocol
- (void)ZHBaseAVplayerView:(ZHBaseAVPlayerView *)avplayerView loadPlayerItemWithStatus:(PlayerItemLoadStatus)status videoTotalTime:(float)totalTime {
    if (status == playerItemLoad_Success) {
        // 视频资源加载完成
        [self videoSourceLoadSuccessActionWithTotalTime:totalTime];
    }
}

- (void)ZHBaseAVplayerView:(ZHBaseAVPlayerView *)avplayerView videoBufferTime:(float)bufferTime {
    float bfb = _videoTotalTime == 0 ? 0: bufferTime/_videoTotalTime;
    [_progressView configBufferProgress:bfb];
}

- (void)ZHBaseAVplayerView:(ZHBaseAVPlayerView *)avplayerView videoPlayTime:(float)playTime {
    if (!_isDraging) {
        _videoCurrentTime = playTime;
        float bfb = _videoTotalTime == 0 ? 0: _videoCurrentTime/_videoTotalTime;
        [_progressView configPlayProgress:bfb];
        [self setTimeLabel];
    }
    if (self.delegate && [self.delegate respondsToSelector:@selector(ZHPlayerView:playTime:)]) {
        [self.delegate ZHPlayerView:self playTime:playTime];
    }
}

- (void)ZHBaseAVplayerView:(ZHBaseAVPlayerView *)avplayerView playStatus:(PlayerPlayStatus)status {
    if (status == play_End) {
        // 视频播放结束
        _playBtn.selected = NO;
    } else if (status == play_Pause) {
        // 暂停
        _playBtn.selected = NO;
    } else if (status == play_Play) {
        // 播放
        _playBtn.selected = YES;
    }
    
    if (self.delegate && [self.delegate respondsToSelector:@selector(ZHPlayerView:playStatus:)]) {
        [self.delegate ZHPlayerView:self playStatus:status];
    }
}

#pragma mark - ZHPlayerGesturesViewProtocol
- (void)gesturesViewTap:(ZHPlayerGesturesView *)view {
    [self hideToolView];
}

@end
